package com.cp.config;

import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.logging.LoggingApplicationListener;
import org.springframework.context.ApplicationEvent;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * Des:
 * 配置log4j2文件前给系统注入一些必要的环境, 方便读取
 *
 * @author XL
 * @Date 2022/1/18 14:41
 */
@SuppressWarnings("all")
@Order(-1)
public class SystemEnvironmentSettingListener extends LoggingApplicationListener{
    /**
     * 应用名称
     */
    private static final String SPRING_NAME = "spring.application.name";

    private static final String LOG4J2_LEVEL = "log4j2.level";

    private static final String LOG4J2_SKIP_JANSI = "log4j.skipJansi";

    private static final String DEFAULT_LOGLEVEL = "info";

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationEnvironmentPreparedEvent) {
            ApplicationEnvironmentPreparedEvent preparedEvent = (ApplicationEnvironmentPreparedEvent) event;
            ConfigurableEnvironment environment = preparedEvent.getEnvironment();
            String applicationName = environment.getProperty(SPRING_NAME);
            String log4j2Level = environment.getProperty(LOG4J2_LEVEL) == null ? DEFAULT_LOGLEVEL : environment.getProperty(LOG4J2_LEVEL).toLowerCase();
            System.setProperty(LOG4J2_SKIP_JANSI, String.valueOf(Boolean.FALSE));
            System.setProperty("applicationName", applicationName);
            System.setProperty("log4j2Level", log4j2Level);
        }
    }
}
